<template>
  <div class="paint-film-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">车漆保护膜管理</span>
        </div>
      </div>
      <h1 class="page-title">车漆保护膜管理</h1>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <router-link to="/paintFilm/add" class="v-button primary">
        <i class="iconfont icon-add"></i> 添加保护膜
      </router-link>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索产品名称"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 车漆保护膜表格 -->
    <div class="v-container">
      <table class="v-table">
        <thead>
          <tr>
            <th width="80">ID</th>
            <th width="120">产品图片</th>
            <th>产品名称</th>
            <th width="130">分类</th>
            <th width="130">厚度(Mil)</th>
            <th width="130">质保</th>
            <th width="200">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="film in filteredFilmList" :key="film.id">
            <td>{{ film.id }}</td>
            <td>
              <div class="film-image">
                <img 
                  :src="film.image" 
                  :alt="film.name" 
                  @click="previewImage(film.image)" 
                />
              </div>
            </td>
            <td>{{ film.name }}</td>
            <td>{{ film.category_name }}</td>
            <td>{{ film.thickness }}</td>
            <td>{{ film.warranty }}</td>
            <td>
              <div class="control">
                <router-link :to="'/paintFilm/edit/' + film.id" class="v-button">
                  <i class="iconfont icon-edit"></i> 编辑
                </router-link>
                <button class="v-button danger" @click="confirmDelete(film)">
                  <i class="iconfont icon-delete1"></i> 删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="!loading && filmList.length === 0">
            <td colspan="6" class="empty-row">
              <i class="iconfont icon-empty"></i>
              {{ searchQuery ? "没有找到匹配的产品" : "暂无数据" }}
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pagination.totalPages > 1">
        <div class="v-pagination">
          <button
            class="v-button"
            :disabled="pagination.page === 1"
            @click="handlePageChange(pagination.page - 1)"
          >
            上一页
          </button>

          <template v-for="page in visiblePages" :key="page">
            <button
              class="v-button"
              :class="{ primary: page === pagination.page }"
              @click="handlePageChange(page)"
            >
              {{ page }}
            </button>
          </template>

          <button
            class="v-button"
            :disabled="pagination.page === pagination.totalPages"
            @click="handlePageChange(pagination.page + 1)"
          >
            下一页
          </button>
        </div>

        <div class="page-info">
          共 {{ pagination.total }} 条，当前 {{ pagination.page }}/{{
            pagination.totalPages
          }} 页
        </div>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="showPreview" class="image-preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="previewImageUrl" alt="预览图" />
        <button class="close-btn" @click="closePreview">
          <i class="iconfont icon-close"></i>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";

const router = useRouter();

// 数据
const filmList = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const showPreview = ref(false);
const previewImageUrl = ref("");

// 分页信息
const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  totalPages: 1,
});

// 获取车漆保护膜列表
const fetchFilms = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      keyword: searchQuery.value
    };
    
    const res = await get("/paintFilm/list", params);
    if (res.code === 200) {
      filmList.value = res.data.list || [];
      pagination.value = {
        page: res.data.pagination.page || 1,
        pageSize: res.data.pagination.pageSize || 10,
        total: res.data.pagination.total || 0,
        totalPages: res.data.pagination.totalPages || 1
      };
    } else {
      vToast.error(res.msg || "获取车漆保护膜列表失败");
    }
  } catch (error) {
    vToast.error("获取车漆保护膜列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.page = 1;
  fetchFilms();
};

const handleSearchClear = () => {
  searchQuery.value = "";
  pagination.value.page = 1;
  fetchFilms();
};

// 过滤后的车漆保护膜列表
const filteredFilmList = computed(() => {
  return filmList.value;
});

// 分页
const handlePageChange = (page) => {
  if (page < 1 || page > pagination.value.totalPages) return;
  pagination.value.page = page;
  fetchFilms();
};

// 计算可见页码
const visiblePages = computed(() => {
  const { page, totalPages } = pagination.value;
  const pages = [];
  const maxVisible = 5;

  if (totalPages <= maxVisible) {
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i);
    }
  } else {
    const half = Math.floor(maxVisible / 2);
    let start = page - half;
    let end = page + half;

    if (start < 1) {
      start = 1;
      end = maxVisible;
    }

    if (end > totalPages) {
      end = totalPages;
      start = end - maxVisible + 1;
    }

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }
  }

  return pages;
});

// 删除确认
const confirmDelete = (film) => {
  vConfirm({
    message: `确定要删除车漆保护膜【${film.name}】吗？`,
    onConfirm: () => deleteFilm(film.id),
  });
};

const deleteFilm = async (id) => {
  try {
    const res = await post("/paintFilm/delete", { id });

    if (res.code === 200) {
      vToast.success("车漆保护膜删除成功");
      fetchFilms();
    } else {
      vToast.error(res.msg || "删除失败");
    }
  } catch (error) {
    vToast.error("删除失败");
    console.error(error);
  }
};

// 图片预览
const previewImage = (url) => {
  previewImageUrl.value = url;
  showPreview.value = true;
};

const closePreview = () => {
  showPreview.value = false;
  previewImageUrl.value = "";
};

// 初始化加载数据
onMounted(() => {
  fetchFilms();
});

</script>

<style scoped lang="less">
.paint-film-page {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        margin-right: 8px;
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .action-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    .search-wrapper {
      flex: 1;
      max-width: 300px;
      margin-left: auto;

      .search-input {
        position: relative;
        display: flex;
        align-items: center;
        background: var(--v-card-bg);
        border-radius: var(--v-card-radius);
        border: 1px solid var(--v-border-color);
        padding: 0 10px;
        height: 36px;

        i {
          color: var(--v-text-light);
          margin-right: 8px;
        }

        input {
          flex: 1;
          border: none;
          background: transparent;
          outline: none;
          color: var(--v-text);

          &::placeholder {
            color: var(--v-text-light);
          }
        }

        .icon-close {
          cursor: pointer;
          margin-left: 8px;

          &:hover {
            color: var(--v-danger);
          }
        }
      }
    }
  }

  .v-container {
    background-color: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    box-shadow: var(--v-shadow);
    padding: 20px;
    margin-top: 30px;
    transition: all 0.3s;
  }

  .v-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid var(--v-border-color);
    }

    th {
      font-weight: bold;
      color: #333;
    }

    tr:hover {
      background-color: #f9f9f9;
    }
  }

  .film-image {
    width: 100px;
    height: 60px;
    overflow: hidden;
    border-radius: 4px;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.3s;
      
      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .control {
    display: flex;
    align-items: center;
    gap: 8px;

    .v-button {
      padding: 0px 8px;
      font-size: 12px;
      min-width: auto;
      height: 32px;
      line-height: 32px;
      background: var(--v-background-pure);
      color: var(--v-sidebar-background);
      border: var(--v-sidebar-background) 1px solid;

      i {
        margin-right: 4px;
      }

      &.danger {
        color: var(--v-danger);
        border-color: var(--v-danger);
      }
    }
  }

  .empty-row {
    text-align: center;
    padding: 20px;
    color: var(--v-text-light);

    .iconfont {
      font-size: 48px;
      margin-bottom: 10px;
      display: block;
    }
  }

  /* 图片预览模态框 */
  .image-preview-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    
    .preview-content {
      position: relative;
      max-width: 90%;
      max-height: 90%;
      
      img {
        max-width: 100%;
        max-height: 80vh;
        border-radius: 8px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
      }
      
      .close-btn {
        position: absolute;
        top: -40px;
        right: 0;
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
        
        &:hover {
          color: var(--v-theme);
        }
      }
    }
  }

  /* 分页样式 */
  .pagination-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--v-border-color);

    .v-pagination {
      display: flex;
      gap: 8px;

      .v-button {
        min-width: 36px;
        height: 36px;
        padding: 0 12px;

        &[disabled] {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }

    .page-info {
      color: var(--v-text-light);
      font-size: 14px;
    }
  }
}
</style>